package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.vo.NotAuditDepotHead;
import com.jsh.erp.service.WorkflowConfigProcess.WorkflowConfigProcessService;
import com.jsh.erp.service.redis.RedisService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.*;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;



@RestController
@RequestMapping(value = "/workflowConfigProcess", produces = "application/json;charset=UTF-8")
@Api(tags = {"审批任务"})
public class WorkflowProcessController {


    @Resource
    private WorkflowConfigProcessService workflowConfigProcessService;
    @Resource
    private RedisService redisService;
    @Resource
    private UserService userService;



    @GetMapping(value = "/Processlist")
    @ApiOperation(value = "待办任务列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = WorkflowProcessDetail.class)
    })
    public String Processlist(@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                          @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                          @RequestParam(value = Constants.SEARCH, required = false) String search,
                          HttpServletRequest request) throws Exception {
        Map<String, String> parameterMap = ParamUtils.requestToMap(request);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String lanCode = redisService.getLanCodeFromSession(request);
        if (pageSize != null && pageSize <= 0) {
            pageSize = 10;
        }
        String offset = ParamUtils.getPageOffset(currentPage, pageSize);
        if (StringUtil.isNotEmpty(offset)) {
            parameterMap.put(Constants.OFFSET, offset);
        }
        String taskTitle = StringUtil.getInfo(search, "taskTitle");
        String flowKey = StringUtil.getInfo(search, "flowKey");
        String userId = redisService.getObjectFromSessionByKey(request,"userId").toString();
        List<WorkflowProcessDetail> list = workflowConfigProcessService.selectByCreate(taskTitle,userId,QueryUtils.offset(parameterMap), QueryUtils.rows(parameterMap),flowKey);
        if (list != null) {
            objectMap.put("total", workflowConfigProcessService.countByCreate(taskTitle,userId,flowKey));
            objectMap.put("rows", list);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/getHistoryInfo")
    @ApiOperation(value = "获取历史记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "defineDetailId", value = "配置id", required = true)
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = WorkflowProcessDetailHis.class)
    })
    public BaseResponseInfo getHistoryInfo(@RequestParam(value = "defineDetailId", required = true) String defineDetailId,
                          HttpServletRequest request) throws Exception {

        List<WorkflowProcessDetailHis> historyInfo = workflowConfigProcessService.getHistoryInfo(defineDetailId);
        return new BaseResponseInfo(ErpInfo.OK.code, historyInfo);
    }


    @GetMapping(value = "/ProcessApproveList")
    @ApiOperation(value = "已办任务列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = WorkflowApproveDetail.class)
    })
    public String ProcessApproveList(@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                              @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                              @RequestParam(value = Constants.SEARCH, required = false) String search,
                              HttpServletRequest request) throws Exception {
        Map<String, String> parameterMap = ParamUtils.requestToMap(request);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String lanCode = redisService.getLanCodeFromSession(request);
        if (pageSize != null && pageSize <= 0) {
            pageSize = 10;
        }
        String offset = ParamUtils.getPageOffset(currentPage, pageSize);
        if (StringUtil.isNotEmpty(offset)) {
            parameterMap.put(Constants.OFFSET, offset);
        }
        String taskTitle = StringUtil.getInfo(search, "taskTitle");
        String flowKey = StringUtil.getInfo(search, "flowKey");
        String userId = redisService.getObjectFromSessionByKey(request,"userId").toString();
        List<WorkflowApproveDetail> list = workflowConfigProcessService.selectApproveByCreate(taskTitle,userId,QueryUtils.offset(parameterMap), QueryUtils.rows(parameterMap),flowKey);
        if (list != null) {
            objectMap.put("total", workflowConfigProcessService.countApproveByCreate(taskTitle,userId,flowKey));
            objectMap.put("rows", list);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }
    @GetMapping(value = "/rejectApproveList")
    @ApiOperation(value = "驳回单据")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = WorkflowApproveDetail.class)
    })
    public String rejectApproveList(@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                                     @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                                     @RequestParam(value = Constants.SEARCH, required = false) String search,
                                     HttpServletRequest request) throws Exception {
        Map<String, String> parameterMap = ParamUtils.requestToMap(request);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        String lanCode = redisService.getLanCodeFromSession(request);
        if (pageSize != null && pageSize <= 0) {
            pageSize = 10;
        }
        String offset = ParamUtils.getPageOffset(currentPage, pageSize);
        if (StringUtil.isNotEmpty(offset)) {
            parameterMap.put(Constants.OFFSET, offset);
        }
        String taskTitle = StringUtil.getInfo(search, "taskTitle");
        String flowKey = StringUtil.getInfo(search, "flowKey");
        String userId = redisService.getObjectFromSessionByKey(request,"userId").toString();
        List<WorkflowApproveDetail> list = workflowConfigProcessService.rejectApproveList(taskTitle,userId,QueryUtils.offset(parameterMap), QueryUtils.rows(parameterMap),flowKey);
        if (list != null) {
            objectMap.put("total", workflowConfigProcessService.rejectApproveCount(taskTitle,userId,flowKey));
            objectMap.put("rows", list);
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.FOUND.name : ErpInfo.FOUND.lanCodeName, ErpInfo.OK.code);
        }
    }
    @RequestMapping(value = "/approve", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "审批", notes = "审批")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true),
            @ApiImplicitParam(name = "approveType", value = "pass/reject", required = true),
            @ApiImplicitParam(name = "approveMsg", value = "审批意见", required = true)
    })
    public String approve(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String approveType = jsonObject.getString("approveType");
        String approveMsg = jsonObject.getString("approveMsg");
        String ids = jsonObject.getString("ids");
        workflowConfigProcessService.batchApproveType(approveType, ids,approveMsg,request);
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @RequestMapping(value = "/deApproval", method = {RequestMethod.POST})
    @ResponseBody
    @ApiOperation(value = "财务反审核", notes = "财务反审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true),
    })
    public String deApproval(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        String lanCode = redisService.getLanCodeFromSession(request);
        String ids = jsonObject.getString("ids");
        workflowConfigProcessService.batchDeApproveType(ids,request);
        return returnJson(objectMap, "zh".equals(lanCode) ? ErpInfo.OK.name : ErpInfo.OK.lanCodeName, ErpInfo.OK.code);
    }

    @GetMapping(value = "/getProgressInfo")
    @ApiOperation(value = "获取进度")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "defineDetailId", value = "配置id", required = true),
            @ApiImplicitParam(name = "processDetailId", value = "任务id", required = true),
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = WorkflowConfigDetail.class)
    })
    public BaseResponseInfo getProgressInfo(@RequestParam(value = "defineDetailId", required = true) String defineDetailId,
                                            @RequestParam(value = "processDetailId", required = true) String processDetailId,
                                           HttpServletRequest request) throws Exception {

        List<WorkflowConfigDetail> historyInfo = workflowConfigProcessService.getProgressInfo(defineDetailId,processDetailId);
        return new BaseResponseInfo(ErpInfo.OK.code, historyInfo);
    }
    @GetMapping(value = "/getProgressByDefaultNumber")
    @ApiOperation(value = "根据单据编号获取进度")
    @ApiResponses({
            @ApiResponse(code = 200,message = "ok",response = WorkflowConfigDetail.class)
    })
    public BaseResponseInfo getProgressByDefaultNumber(@RequestParam(value = "defaultNumber", required = true) String defaultNumber,
                                            HttpServletRequest request) throws Exception {

        List<WorkflowConfigDetail> historyInfo = workflowConfigProcessService.getProgressByMaterialId(defaultNumber);
        return new BaseResponseInfo(ErpInfo.OK.code, historyInfo);
    }

    @GetMapping(value = "/reviewedNumber")
    @ApiOperation(value = "通知 待审批的数量")
    public Long reviewedNumber(HttpServletRequest request) throws Exception {
        User userInfo = userService.getCurrentUser();
        return workflowConfigProcessService.reviewedNumber(userInfo.getId());
    }

    @GetMapping(value = "/reviewedNotAuditNumber")
    @ApiOperation(value = "待审批数量")
    public BaseResponseInfo reviewedNotAuditNumber(HttpServletRequest request) throws Exception {
        User userInfo = userService.getCurrentUser();
        List<NotAuditDepotHead> depotHeadList = workflowConfigProcessService.notAuditSubTypeCount(userInfo.getId());
        return new BaseResponseInfo(ErpInfo.OK.code, depotHeadList);
    }
}
